package com.ruitu.mall_98_2.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.support.glide.transformations.GlideImageLoader;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.view.EvaluateView;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.mvp.contract.CommentContract;
import com.ruitu.mall_98_2.mvp.model.CommentModel;
import com.ruitu.mall_98_2.mvp.presenter.CommentPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.order.OrderDetail;
import com.ruitu.router_module.bean.order.SmallOrder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MultipartBody;

public class CommentActivity extends MyBaseActivity<CommentPresenter, CommentModel> implements CommentContract.View {
    private EditText et_evaluate_content;
    private EvaluateView evaluateview_commotidy;
    private EvaluateView evaluateview_merchant_services;
    private EvaluateView evaluate_logistics_services;
    private TextView tv_commit;
    private GridView gv_1;

    private ImageView iv_commodity;
    private TextView tv_commodity_name;
    private TextView tv_commodity_info;
    private TextView tv_commodity_price;
    private TextView tv_commodity_num;
    private String commotidy = "5";
    private String merchant_services = "5";
    private String logistics_services = "5";
    private ArrayList<String> list = new ArrayList<>();
    private ArrayList<ImageItem> arrayList;

    private EvaluateAdapter adapter;
    private int maxTotal = 3;
    private final int PHOTO_REQUEST_CODE = 999;
//    private SmallOrder smallOrder;
    private SmallOrder orderDetail;
    private List<File> files;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_comment;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("订单评论");
        orderDetail = (SmallOrder) getIntent().getExtras().get("smallOrder");
        et_evaluate_content = findViewById(R.id.et_evaluate_content);
        evaluateview_commotidy = findViewById(R.id.evaluateview_commotidy);
        evaluateview_merchant_services = findViewById(R.id.evaluateview_merchant_services);
        evaluate_logistics_services = findViewById(R.id.evaluate_logistics_services);
        iv_commodity = findViewById(R.id.iv_commodity);
        tv_commodity_name = findViewById(R.id.tv_commodity_name);
        tv_commodity_info = findViewById(R.id.tv_commodity_info);
        tv_commodity_price = findViewById(R.id.tv_commodity_price);
        tv_commodity_num = findViewById(R.id.tv_commodity_num);
        tv_commit = findViewById(R.id.tv_commit);
        gv_1 = findViewById(R.id.gv_1);
        tv_commit.setOnClickListener(this);

        files = new ArrayList<>();
        init();

    }

    private String odId;
    private String goodsId;
    private String goodsModelId;

    private void init() {
        if (orderDetail != null) {
            Glide.with(this).load(Config.BASE_URL + orderDetail.getGoodsUrl()).apply(Arad.opts).into(iv_commodity);
            tv_commodity_name.setText(orderDetail.getGoodsName());
            tv_commodity_info.setText(orderDetail.getSkuContent());
            tv_commodity_price.setText("￥" + orderDetail.getGoodsPrice());
            tv_commodity_num.setText("x" + orderDetail.getQuantity());
            odId = orderDetail.getId();
            goodsId = orderDetail.getGoodsId();
            goodsModelId = orderDetail.getGoodsSkuId();
        }
        evaluateview_commotidy.setOnEvaluateStar(new EvaluateView.OnEvaluateStarListener() {
            @Override
            public void OnStarNum(int num) {
                commotidy = num + "";
            }
        });

        evaluateview_merchant_services.setOnEvaluateStar(new EvaluateView.OnEvaluateStarListener() {
            @Override
            public void OnStarNum(int num) {
                merchant_services = num + "";
            }
        });

        evaluate_logistics_services.setOnEvaluateStar(new EvaluateView.OnEvaluateStarListener() {
            @Override
            public void OnStarNum(int num) {
                logistics_services = num + "";
            }
        });

        adapter = new EvaluateAdapter(list, this);
        gv_1.setAdapter(adapter);
        adapter.setDataList(list);
        adapter.setOnItemClickListener(new EvaluateAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                Intent intent = new Intent(CommentActivity.this, ImageGridActivity.class);
                if (position == list.size() && list.size() != maxTotal) {
                    initImagePicker(maxTotal - list.size());
                    startActivityForResult(intent, PHOTO_REQUEST_CODE);
                } else {
                    intent = new Intent(CommentActivity.this, ImageViewerActivity.class);
                    intent.putExtra(ImageViewerActivity.IMG_DATA, list);
                    intent.putExtra(ImageViewerActivity.IMG_POSITION, position);
                    startActivityForResult(intent, ImageViewerActivity.IMG_REQUEST_CODE);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_commit) {
            showProgress();
            MultipartBody multipartBody = mPresenter.saveCommentScore(odId, AppHolder.instance().getUser().getAccountId(), commotidy, merchant_services, logistics_services, et_evaluate_content.getText().toString(), goodsId, goodsModelId, files);
            mPresenter.saveCommentScore(multipartBody);
        }
    }

    @Override
    public void setCommentSuc() {
        Arad.bus.post(new EventModel(18122000));
        finish();
    }

    static class EvaluateAdapter extends BaseAdapter {

        private List<String> data;
        private Context mContext;
        private LayoutInflater inflater;

        //最多显示图片数量
        private int maxImages = 4;
        private OnItemClickListener onItemClickListener;

        public EvaluateAdapter(List<String> datas, Context context) {
            this.data = datas;
            this.mContext = context;
            inflater = LayoutInflater.from(context);
        }

        public void setDataList(List<String> datas) {
            this.data = datas;
            notifyDataSetChanged();
        }

        /**
         * 让GridView中的数据数目加1最后一个显示+号
         * 当到达最大张数时不再显示+号
         *
         * @return 返回GridView中的数量
         */
        @Override
        public int getCount() {
            int count = data == null ? 1 : data.size() + 1;
            if (count >= maxImages) {
                return data.size();
            } else {
                return count;
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_evaluate_img, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
//        代表+号之前显示正常的图片
            if (data != null && position < data.size()) {
                final File file = new File(data.get(position));
                Glide.with(mContext)
                        .load(file)
                        .into(viewHolder.ivimage);
            } else {
                Glide.with(mContext)
                        .load(R.mipmap.image_add)
                        .into(viewHolder.ivimage);
                viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
            }
            viewHolder.ivimage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickListener.onItemClick(view, position);
                }
            });
            return convertView;
        }

        public class ViewHolder {
            public final ImageView ivimage;
            public final View root;

            public ViewHolder(View root) {
                ivimage = (ImageView) root.findViewById(R.id.iv_image);
                this.root = root;
            }
        }

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        interface OnItemClickListener {
            void onItemClick(View itemView, int position);
        }

    }

    public void initImagePicker(int maxTotal) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);
        imagePicker.setSelectLimit(maxTotal);
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == PHOTO_REQUEST_CODE) {
                arrayList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < arrayList.size(); i++) {
                    list.add(arrayList.get(i).path);
                    files.add(new File(arrayList.get(i).path));
                }
                adapter.setDataList(list);
            }

            if (requestCode == 99) {
                if (data != null) {
                    list = data.getStringArrayListExtra(ImageViewerActivity.IMG_DATA);
                    for (int i = 0; i < list.size(); i++) {
                        files.add(new File(list.get(i)));
                    }

                    adapter.setDataList(list);
                }
            }
        }

    }

}
